﻿using BlazorHero.CleanArchitecture.Application.Interfaces.Repositories;
using BlazorHero.CleanArchitecture.Domain.Entities.Members;
using BlazorHero.CleanArchitecture.Shared.Wrapper;
using MediatR;
using Microsoft.Extensions.Localization;
using System.Threading;
using System.Threading.Tasks;

namespace BlazorHero.CleanArchitecture.Application.Features.Members.Commands.Delete
{
    public class DeleteMemberCommand : IRequest<Result<long>>
    {
        public long Id { get; set; }
    }

    internal class DeleteMemberCommandHandler : IRequestHandler<DeleteMemberCommand, Result<long>>
    {
        private readonly IUnitOfWork<long> _unitOfWork;
        private readonly IStringLocalizer<DeleteMemberCommandHandler> _localizer;

        public DeleteMemberCommandHandler(IUnitOfWork<long> unitOfWork, IStringLocalizer<DeleteMemberCommandHandler> localizer)
        {
            _unitOfWork = unitOfWork;
            _localizer = localizer;
        }

        public async Task<Result<long>> Handle(DeleteMemberCommand command, CancellationToken cancellationToken)
        {
            var member = await _unitOfWork.Repository<Member>().GetByIdAsync(command.Id);
            if (member != null)
            {
                await _unitOfWork.Repository<Member>().DeleteAsync(member);
                await _unitOfWork.Commit(cancellationToken);
                return await Result<long>.SuccessAsync(member.Id, _localizer["Member Deleted"]);
            }
            else
            {
                return await Result<long>.FailAsync(_localizer["Member Not Found!"]);
            }
        }
    }
}
